<?php
/**
 * 菜谱Service
 */

declare (strict_types = 1);

namespace app\school\service;

use app\common\model\Brand;
use app\common\model\Dose;
use app\common\model\Meal;
use app\common\model\Menu;
use app\common\model\Spec;
use app\common\model\Type;
use app\school\exception\ApiServiceException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class MenuService extends ApiBaseService
{
    protected Menu $model;

    public function __construct()
    {
        $this->model = new Menu();
    }

    /**
     * 列表
     * @param $param
     * @param $page
     * @param $limit
     * @return array
     * @throws ApiServiceException
     */
    public function getList($param, $page, $limit)
    {
        try {
            $start_end = getstart();
            $start     = $start_end['start'];
            $end       = $start_end['end'];
            if (! isset($param['tags'])) {
                $param['tags'] = 0;
            }
            $dose = Dose::with(['school'])
                ->scope('ApiWhere', $param)
                ->where('week', 'between', [$start, $end])
                ->column('detail');
            $meal_id_list = [];
            foreach ($dose as $key => $value) {
                $value          = json_decode($value, true);
                $meal_id_list[] = array_column($value, 'meal_id');
            }
            $meal_id_list = array_reduce($meal_id_list, function ($carry, $item) {
                return array_merge($carry, $item);
            }, []);
            $menu_list    = Meal::whereIn('id', $meal_id_list)->column('detail');
            $menu_id_list = [];
            foreach ($menu_list as $key => $value) {
                $value          = json_decode($value, true);
                $menu_id_list[] = array_column($value, 'menu_id');
            }
            $menu_id_list = array_reduce($menu_id_list, function ($carry, $item) {
                return array_merge($carry, $item);
            }, []);

            $data = $this->model
                ->scope('ApiWhere', $param)
                ->select()
                ->each(function ($item, $key) use ($menu_id_list, $param) {
                    if ($param['tags'] == 1) {
                        $menu_list = Menu::whereIn('id', $menu_id_list)->select();
                        foreach ($menu_list as $k => $v) {
                            if ($item['id'] == $v['old_id']) {
                                $item['detail'] = $v['detail'];
                            }
                        }
                    }

                    $detail = [];
                    foreach ($item['detail'] as $key => $value) {
                        $detail[$key]['type'] = Type::where('id', $value['type_id'])->find();

                        $detail[$key]['brand'] = Brand::where('id', $value['brand_id'])->find();

                        $detail[$key]['spec'] = Spec::where('id', $value['spec_id'])->find();
                    }
                    $item['detail'] = $detail;
                    return $item;

                });
        } catch (DataNotFoundException | ModelNotFoundException $e) {
            $data = [];
        } catch (DbException $e) {
            throw new ApiServiceException('查询列表失败，信息' . $e->getMessage());
        }

        return $data;
    }

    /**
     * 添加
     * @param $param
     * @return bool
     */
    public function createData($param): bool
    {
        $result = $this->model::create($param);
        return (bool) $result;
    }

    /**
     * 数据详情
     * @param $id
     * @return array
     * @throws ApiServiceException
     */
    public function getDataInfo($id): array
    {
        $data = $this->model->where('id', '=', $id)->findOrEmpty();
        if ($data->isEmpty()) {
            throw new ApiServiceException('数据不存在');
        }
        return $data->toArray();
    }

    /**
     * 修改
     * @param $id
     * @param $param
     * @return bool
     * @throws ApiServiceException
     */
    public function updateData($id, $param): bool
    {
        $data = $this->model->where('id', '=', $id)->findOrEmpty();
        if ($data->isEmpty()) {
            throw new ApiServiceException('数据不存在');
        }
        $result = $data->save($param);

        if (! $result) {
            throw new ApiServiceException('更新失败');
        }

        return true;
    }

    /**
     * 删除
     * @param mixed $id
     * @return bool
     * @throws ApiServiceException
     */
    public function deleteData($id): bool
    {
        $result = $this->model::destroy(function ($query) use ($id) {
            $query->whereIn('id', $id);
        });

        if (! $result) {
            throw new ApiServiceException('更新失败');
        }

        return true;
    }

}
